package cn.hhy.hrm.config;

import cn.hhy.hrm.vo.SmsCodeVo;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SmsCodeCheckFilter extends OncePerRequestFilter {


    private AuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1.判断url是短信登录
        if(new AntPathMatcher().match("/smslogin",request.getRequestURI())){

            //2.获取验证码
            String code = request.getParameter("code");
            String phone = request.getParameter("phone");
            SmsCodeVo smsCodeVo =(SmsCodeVo)request.getSession().getAttribute("sms:code");


            //3.核对验证码，假设验证码是 1234
            if(null == code || smsCodeVo == null || smsCodeVo.getCode() == null || smsCodeVo.getPhone() == null ||
                    !smsCodeVo.getCode().equals(code) || !smsCodeVo.getPhone().equals(phone)){

                //4.登录失败，走认证失败处理器
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response, new SmsAuthException("验证码错误"));

                //不放行
                return ;
            }

        }
        //5.否则放行
        filterChain.doFilter(request,response);
    }

    public void setMyAuthenticationFailureHandler(AuthenticationFailureHandler myAuthenticationFailureHandler) {
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }

}